﻿using SqlSugar;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace SunnyPaine.Autofac.Extension.SqlSugar.Util
{
    /// <summary>
    /// 提供一个属性信息解析工具。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    internal class PropertyInfoParser<T> where T : class, new()
    {
        #region 私有变量
        /// <summary>
        /// 类的属性信息字典。
        /// </summary>
        private readonly Dictionary<string, PropertyInfo> propertyInfoDict;
        #endregion


        #region 构造方法
        internal PropertyInfoParser()
        {
            this.propertyInfoDict = new Dictionary<string, PropertyInfo>();
        }
        #endregion


        #region 公共方法
        /// <summary>
        /// 初始化类的属性信息。
        /// </summary>
        internal void InitClassPropertyInfo()
        {
            PropertyInfo[] pis = typeof(T).GetProperties();
            foreach (PropertyInfo pi in pis)
            {
                SugarColumn sugarColumnAttribute = pi.GetCustomAttribute<SugarColumn>();
                if (sugarColumnAttribute != null)
                {
                    if (sugarColumnAttribute.IsIgnore)
                    {
                        continue;
                    }
                    this.propertyInfoDict.Add(sugarColumnAttribute.ColumnName, pi);
                }
                else
                {
                    this.propertyInfoDict.Add(pi.Name, pi);
                }
            }
        }

        /// <summary>
        /// 将DataTable转换为List
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        internal List<T> DataTable2List(DataTable data)
        {
            List<T> list = new List<T>();

            //DataTable拿到的是数据库表的列字段名
            foreach (DataRow row in data.Rows)
            {
                T t = new T();
                foreach (DataColumn column in data.Columns)
                {
                    if (!this.propertyInfoDict.ContainsKey(column.ColumnName))
                    {
                        continue;
                    }
                    this.propertyInfoDict[column.ColumnName].SetValue(t, row[column]);
                }
                list.Add(t);
            }
            return list;
        }
        #endregion
    }
}
